package model

import (
	"fmt"
	"gowork/distributionRuleManagement/utils"
	"math/rand"
	"sync"
	"time"
)

type Adviser struct {
	Id int64 `xorm:"pk autoincr"`
	TypeId int64
	TypeName string
	Name string
	CreatedAt time.Time
	UpdatedAt time.Time
}

type AuthorizationRecord struct {
	Id int64 `xorm:"pk autoincr"`
	AuthorizedPersonOId int64
	AuthorizedPerson string
	CoverAuthorizedPersonId int64
	CoverAuthorizedPerson string
	CustomerName string
	CustomerId int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type DistributionRuleManagement struct {
	Id int64 `xorm:"pk autoincr"`
	NutritionistId int64
	NutritionistName string
	DepartmentName string
	DayAuthorizationsNumber int
	LastModifiedBy string
	Remarks string
	CreatedAt time.Time
	UpdatedAt time.Time
}

type HolidayManagement struct {
	Id int64 `xorm:"pk autoincr"`
	NutritionistId int64
	NutritionistName string
	DepartmentName string
	HolidayStartTime time.Time
	HolidayEndTime time.Time
	CreatedAt time.Time
	UpdatedAt time.Time
}

var lock sync.Mutex

func (distributionRuleManagement *DistributionRuleManagement)ToGrantAuthorization(nId int64, random string)(map[string]interface{}, error){

	w := new(utils.Worker)

	if random == "2"{
		var drmList []*DistributionRuleManagement
		x.SQL("select * from distribution_rule_management drm where drm.day_authorizations_number > (select count(id) from authorization_record ar where cover_authorized_person_id = drm.nutritionist_id and created_at like ?) and drm.nutritionist_id not in (select nutritionist_id from holiday_management where holiday_start_time < ? and holiday_end_time > ?)", time.Now().Format("2006-01-02")+"%", time.Now().Format("2006-01-02 15:04:05"), time.Now().Format("2006-01-02 15:04:05")).Find(&drmList)

		fmt.Println("adrmListList：", drmList)

		randomAdviser := drmList[rand.Intn(len(drmList))]
		var a = AuthorizationRecord{
			Id:                      w.GetId(),
			CoverAuthorizedPersonId: randomAdviser.NutritionistId,
			CoverAuthorizedPerson:   randomAdviser.NutritionistName,
			CreatedAt:               time.Now(),
			UpdatedAt:               time.Now(),
		}
		x.Insert(&a)

	}else {

		var hm HolidayManagement
		x.SQL("select * from holiday_management where nutritionist_id = ? and holiday_start_time < ? and holiday_end_time > ?", nId, time.Now().Format("2006-01-02 15:04:05"), time.Now().Format("2006-01-02 15:04:05")).Get(&hm)
		if hm.Id != 0{
			return map[string]interface{}{"message": "该营养师今日休息", "code": 400}, nil
		}

		lock.Lock()

		//count, err := x.SQL("select * from  authorization_record where cover_authorized_person_id = ? and created_at like ?", nId, time.Now().Format("2006-01-02")+"%").Count()
		count, err := x.Where("cover_authorized_person_id = ?", nId).And("created_at like ?", time.Now().Format("2006-01-02")+"%").Count(new(AuthorizationRecord))
		if err != nil {

			lock.Unlock()

			return nil, err
		}

		fmt.Println("count：", count)

		var dr DistributionRuleManagement
		x.Where("nutritionist_id = ?", nId).Get(&dr)
		if dr.Id != 0 {
			if count >= int64(dr.DayAuthorizationsNumber) {

				lock.Unlock()

				return map[string]interface{}{"message": "今日授权数已达上限", "code": 400}, nil
			}
		} else {
			if count >= 4 {

				lock.Unlock()

				return map[string]interface{}{"message": "今日授权数已达上限", "code": 400}, nil
			}
		}

		var a = AuthorizationRecord{
			Id:                      w.GetId(),
			CoverAuthorizedPersonId: nId,
			CreatedAt:               time.Now(),
			UpdatedAt:               time.Now(),
		}
		x.Insert(&a)

		lock.Unlock()
	}

	return map[string]interface{}{"message": "成功","code":200}, nil
}